package com.pansoft.openplanet.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.util.FileDeleteUtil;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.account.model.EthBean;
import com.pansoft.openplanet.account.util.EthAccountGenerator;
import com.pansoft.openplanet.activity.CreateWalletActivity;
import com.pansoft.openplanet.activity.MyWalletActivity;
import com.pansoft.openplanet.activity.SetupAvatarActivity;
import com.pansoft.openplanet.activity.TCBaseActivity;
import com.pansoft.openplanet.activity.TabBottomActivityForTalkChain;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.constant.TalkChainConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.LoginFlowManager;
import com.pansoft.openplanet.util.TCAccountManager;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.widget.TCLoadingDataView;
import com.utilcode.util.ToastUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

import io.reactivex.disposables.Disposable;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 通过主账户恢复所有子钱包
 * Created by will on 18-3-27.
 */

public class RestoreByMnemonicFragment extends BaseFragment implements View.OnClickListener {

    private static final String TAG = "RestoreByMnemonicFragment";
    private String imUserId, number, userName, menonic;
    private EditText editText1, editText2, editText3, editText4, editText5, editText6,
            editText7, editText8, editText9, editText10, editText11, editText12;

    private AccountDao accountDao;
    //默认存放keysTORE的 文件夹
    private String basePath;
    private Account account;
    private String avatar;
    private TCAccountManager tcAccountManager;
    private String ethAddress;
    private String loginPwd = "";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.talk_chain_activity_verify_token, null);

        number = getActivity().getIntent().getExtras().getString("number");
        userName = getActivity().getIntent().getExtras().getString("userName");
        avatar = getActivity().getIntent().getStringExtra("avatar");
        loginPwd = getActivity().getIntent().getStringExtra("loginPwd");

        editText1 = view.findViewById(R.id.et_1);
        editText2 = view.findViewById(R.id.et_2);
        editText3 = view.findViewById(R.id.et_3);
        editText4 = view.findViewById(R.id.et_4);
        editText5 = view.findViewById(R.id.et_5);
        editText6 = view.findViewById(R.id.et_6);
        editText7 = view.findViewById(R.id.et_7);
        editText8 = view.findViewById(R.id.et_8);
        editText9 = view.findViewById(R.id.et_9);
        editText10 = view.findViewById(R.id.et_10);
        editText11 = view.findViewById(R.id.et_11);
        editText12 = view.findViewById(R.id.et_12);
        Button tvNext = view.findViewById(R.id.tv_next);
        tvNext.setOnClickListener(this);

        accountDao = new AccountDao(getActivity());

        basePath = TalkChainConstant.getDataFilePath(getActivity()) + File.separator + number;
        tcAccountManager = new TCAccountManager(getActivity());
        return view;

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_next) {
            verifyMnemonic();

        }
    }

    private void verifyMnemonic() {

        if (editText1.getText().toString().equals("") || editText2.getText().toString().equals("")
                || editText3.getText().toString().equals("") || editText4.getText().toString().equals("")
                || editText5.getText().toString().equals("") || editText6.getText().toString().equals("")
                || editText7.getText().toString().equals("") || editText8.getText().toString().equals("")
                || editText9.getText().toString().equals("") || editText10.getText().toString().equals("")
                || editText11.getText().toString().equals("") || editText12.getText().toString().equals("")) {
            ToastUtils.showShort(R.string.open_planet_incomplete_mnemonic_hint);
        } else {
            if (EnvironmentVariable.getPassword() == null || "".equals(EnvironmentVariable.getPassword())) {
                ToastUtils.showShort(R.string.open_planet_password_not_exist_hint);
                return;
            }

            StringBuilder stringBuilder = new StringBuilder();
            menonic = stringBuilder.append(editText1.getText().toString())
                    .append(" ")
                    .append(editText2.getText().toString())
                    .append(" ")
                    .append(editText3.getText().toString())
                    .append(" ")
                    .append(editText4.getText().toString())
                    .append(" ")
                    .append(editText5.getText().toString())
                    .append(" ")
                    .append(editText6.getText().toString())
                    .append(" ")
                    .append(editText7.getText().toString())
                    .append(" ")
                    .append(editText8.getText().toString())
                    .append(" ")
                    .append(editText9.getText().toString())
                    .append(" ")
                    .append(editText10.getText().toString())
                    .append(" ")
                    .append(editText11.getText().toString())
                    .append(" ")
                    .append(editText12.getText().toString())
                    .toString();

            account = new Account();
            //恢复keystore的文件路径
            File file = new File(basePath);
            //清空文件夹
            if (file != null) {
                FileDeleteUtil.delete(file);
            }
            file = new File(basePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            accountDao.deleteByCurentImuserId();
            TCLoadingDataView.show(getContext(), R.string.open_planet_recovering);
            Disposable disposable = EthAccountGenerator.recoverAccountByMnemoric(basePath, menonic, IPAssetsConstant.ChainEnum.ETH,
                    new EthAccountGenerator.GeneratorListener() {
                        @Override
                        public void generatorSuccess(final EthBean ethBean) {

                            if (accountDao.getAccount(ethBean.getEthAddress().toLowerCase()) != null) {
                                //账户已存在
                                TCLoadingDataView.dismiss();
                                showCoverAlertDialog();
                                return;
                            } else {
                                account.setAddress(ethBean.getEthAddress());
                                account.setAccountAvatar(avatar);
                                account.setAcccountName(userName);
                                account.setFileName(ethBean.getKeyStoreFilePath());
                                account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                                account.setPublicKey(ethBean.getEcKeyPair().getPublicKey().toString());
                                account.setMaster(true);
                                account.setCurrentShow(true);
                                account.setMainAccoutAddress(ethBean.getEthAddress());
                                account.setEnable(false);
                                accountDao.insertOrReplace(account);

                                //判断恢复的钱包地址是否跟服务器一致
                                if (!"".equals(EnvironmentVariable.getProperty("tc_ethAddress", ""))) {
                                    if (!account.getAddress().toLowerCase()
                                            .equals(EnvironmentVariable.getProperty("tc_ethAddress", "").toLowerCase())) {
                                        FileDeleteUtil.delete(new File(ethBean.getKeyStoreFilePath()));
                                        accountDao.delete(account.getAddress());
                                        TCLoadingDataView.dismiss();
                                        showFailAlert(ResStringUtil.getString(R.string
                                                .open_planet_recovering_fail_inconsistency_account));
                                        return;
                                    }
                                }
                                final String ethPublicKey = ethBean.getEcKeyPair().getPublicKey().toString();
                                final String ethPrivateKey = ethBean.getEcKeyPair().getPrivateKey().toString();
                                final String address = ethBean.getEthAddress();
                                //检查通讯密钥并 上传服务器
//                                tcAccountManager.addChildWallet(ethPublicKey, ethPrivateKey, address, "",
//                                        "", IPAssetsConstant.ChainEnum.ETH
//                                                .chainName, new TCAccountManager.AccountManagerListener() {
//                                            @Override
//                                            public void onSuccess(Object object) {
                                //新建成功后 检查通讯公钥
                                tcAccountManager.checkAndUpdateMessageKey(EnvironmentVariable.getProperty(CHAT_USER_ID),false,
                                        new TCAccountManager.AccountManagerListener<String>() {
                                            @Override
                                            public void onSuccess(String rsaPublicKey) {
                                                TCLoadingDataView.dismiss();
                                                sendToServer(address, ethPublicKey, new File(ethBean.getKeyStoreFilePath()), rsaPublicKey);
                                            }

                                            @Override
                                            public void onFail(String fail) {
                                                TCLoadingDataView.dismiss();
                                                ToastUtil.showToast(getContext(),getResources().getString(R.string.openplanet_tokencheck_text2));
                                            }
                                        });

//                                            }
//
//                                            @Override
//                                            public void onFail(String fail) {
//                                                ToastUtil.showToast(getContext(), "服务异常,请重试");
//                                            }
//                                        });


//                                sendToServer(ethBean.getEthAddress(),ethBean.getEcKeyPair().getPublicKey().toString(), new File(ethBean.getKeyStoreFilePath()), rsaPublicKey);
                            }
                        }

                        @Override
                        public void generatorFail() {
                            TCLoadingDataView.dismiss();
                            ToastUtils.showShort(R.string.open_planet_recovering_fail);
                        }
                    });


            ((TCBaseActivity) getActivity()).addDisposable(disposable);
        }
    }


    //保存结果到服务器
    private void sendToServer(final String address, String publicKey, final File realFile, String rsaPublicKey) {
        if (address == null || "".equals(address) || publicKey == null || "".equals(publicKey)) {
            showFailAlert(ResStringUtil.getString(R.string.open_planet_recovering_fail_code_300));
            return;
        }
        if (rsaPublicKey == null || "".equals(rsaPublicKey)) {
            showFailAlert(ResStringUtil.getString(R.string.open_planet_recovering_fail_code_301));
            return;
        }

        TCLoadingDataView.show(getActivity(), getResources().getString(R.string.open_planet_asset_restore_verifying));
        final HashMap<String, String> map = new HashMap<>();
        map.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        map.put("ethAddress", address);
        map.put("ethPublicKey", publicKey);
        map.put("comPublicKey", rsaPublicKey);


        TCRequestUtil.postOAuthRequest(TAG, "user/updateUserEthPublicKeyAndAddress", map,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        TCLoadingDataView.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(response);

                            if (jsonObject.has("result")
                                    && jsonObject.getString("result")
                                    .equals("success")) {
                                //创建账户成功，本地持久化账户信息
                                //saveAccount();
                                //显示成功对话框
                                //showSuccessAlert();
                                //存入env
                                EnvironmentVariable.setProperty("tc_ethAddress", address);
                                //结束创建钱包的状态
                                EnvironmentVariable.setProperty(LoginFlowManager.getCreateWalletStateKey(number), "false");
                                ethAddress = address;
                                recoverChildWallet(ethAddress);
                                //goToNextPage();
                            } else {
                                //请求服务器失败，删除本地的keystore文件
                                if (realFile != null) {
                                    FileDeleteUtil.delete(realFile);
                                }
                                showFailAlert(getResources().getString(R.string.open_planet_asset_restore_recovery_fails));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                            if (realFile != null) {
                                FileDeleteUtil.delete(realFile);
                            }
                            showFailAlert(getResources().getString(R.string.open_planet_asset_restore_recovery_fails));
                        }
                    }

                    @Override
                    public void onFail(String error) {
                        TCLoadingDataView.dismiss();
                        if (realFile != null) {
                            FileDeleteUtil.delete(realFile);
                        }
                        showFailAlert(getResources().getString(R.string.open_planet_asset_restore_recovery_fails_net));
                    }
                });
    }

    //恢复子钱包
    private void recoverChildWallet(String mainAddress) {
        TCLoadingDataView.show(getActivity(), getResources().getString(R.string.open_planet_asset_restore_restoring_child_wallet));
        tcAccountManager.restoreChildWallet(mainAddress, new TCAccountManager.AccountManagerListener<String>() {
            @Override
            public void onSuccess(String object) {
                TCLoadingDataView.dismiss();
                //设置账户可用
                account.setEnable(true);
                accountDao.insertOrReplace(account);
                goToNextPage();
            }

            @Override
            public void onFail(String fail) {
                TCLoadingDataView.dismiss();
                new AlertDialog.Builder(getActivity())
                        .setTitle(R.string.common_text_hint)
                        .setCancelable(false)
                        .setMessage(getResources().getString(R.string.open_planet_asset_restore_child_wallet_fails))
                        .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                recoverChildWallet(ethAddress);
                            }
                        })
                        .create()
                        .show();
            }
        });

    }

    private void goToNextPage() {
        //如果从我的钱包界面过来，跳回原界面
        if (getActivity().getIntent().hasExtra(CreateWalletActivity.LAST_ACTIVITY)) {
            String lastActivity = getActivity().getIntent().getStringExtra(CreateWalletActivity.LAST_ACTIVITY);
            if ("myWallet".equals(lastActivity)) {
                Intent intent1 = new Intent(getActivity(), MyWalletActivity.class);
                ActivityCompat.finishAffinity(getActivity());
                return;
            }

        }


        if (EnvironmentVariable.getProperty("old_user").equals("1") &&
                !EnvironmentVariable.getProperty(LoginFlowManager.getIsRegisterKey(number), "").equals("true")) {
            Intent intent1 = new Intent(getActivity(), TabBottomActivityForTalkChain.class);
            intent1.putExtra("unDoCheck", "true");//从登录界面跳转无需再次检查是否升级
            //intent1.putExtra("listobj", (Serializable) mainMenus);
            getActivity().startActivity(intent1);
            ActivityCompat.finishAffinity(getActivity());

        } else {
            Intent intent = new Intent(getActivity(), SetupAvatarActivity.class);
            intent.putExtra("id", EnvironmentVariable.getProperty(CHAT_USER_ID));
            intent.putExtra("userName", userName);
            intent.putExtra("number", number);
            startActivity(intent);
        }
    }

    private void showFailAlert(String message) {
        if (message == null)
            message = ResStringUtil.getString(R.string.open_planet_recovering_fail_retry);
        new AlertDialog.Builder(getActivity())
                .setTitle(R.string.common_text_hint)
                .setMessage(message)
                .setPositiveButton(R.string.common_text_confirm, null)
                .create()
                .show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ((TCBaseActivity) getActivity()).dispose();
    }

    /**
     * 提示是否覆盖的
     */
    private void showCoverAlertDialog() {
        new AlertDialog.Builder(getActivity())
                .setTitle(R.string.common_text_hint)
                .setMessage(getResources().getString(R.string.open_planet_asset_restore_account_import))
                .setPositiveButton(R.string.common_text_confirm, null)
                .create()
                .show();

    }
}
